package org.nox.helloseries.rest;

import java.util.List;

import org.nox.helloseries.core.services.configuration.serie.SerieConfigurationService;
import org.nox.helloseries.core.services.configuration.tracker.TrackerConfigurationService;
import org.nox.helloseries.domain.NomTracker;
import org.nox.helloseries.domain.Serie;
import org.nox.helloseries.domain.Tracker;
import org.nox.helloseries.factory.HelloSeriesServiceFactory;

import restx.annotations.GET;
import restx.annotations.POST;
import restx.annotations.RestxResource;
import restx.factory.Component;
import restx.security.PermitAll;

import com.google.common.base.Optional;

/**
 * Hello world!
 */
@Component
@RestxResource
public class HelloSeriesConfigurationResource
{

    private TrackerConfigurationService trackerConfigurationService = HelloSeriesServiceFactory.createOrGetService( TrackerConfigurationService.class );

    private SerieConfigurationService serieConfigurationService = HelloSeriesServiceFactory.createOrGetService( SerieConfigurationService.class );

    @GET( "/configuration/trackers" )
    @PermitAll
    public List<Tracker> getTrackers( Optional<Boolean> actif )
    {
        if ( actif.isPresent() && actif.get() )
        {
            return trackerConfigurationService.getTrackersActifs();
        }
        return trackerConfigurationService.getTrackers();
    }

    @POST( "/configuration/trackers" )
    @PermitAll
    public String updateTrackers( List<Tracker> trackersToBeUpdated )
    {
        try
        {
            trackerConfigurationService.updateTrackers( trackersToBeUpdated );
        }
        catch ( Exception e )
        {
            return "Sauvegarde des trackers KO, cause : " + e.getMessage();
        }

        return "Sauvegarde des trackers suceed";
    }

    @GET( "/configuration/tracker/{nomTracker}" )
    @PermitAll
    public Tracker getTrackers( String nomTracker )
    {
        return trackerConfigurationService.getTracker( NomTracker.valueOf( nomTracker ) );
    }

    @GET( "/configuration/series" )
    @PermitAll
    public List<Serie> getSeries( Optional<Boolean> actif )
    {
        if ( actif.isPresent() && actif.get() )
        {
            return serieConfigurationService.getSeriesActives();
        }
        return serieConfigurationService.getSeries();
    }

    @POST( "/configuration/series" )
    @PermitAll
    public String saveSerie( List<Serie> series )
    {
        try
        {
            serieConfigurationService.saveSeries( series );
        }
        catch ( Exception e )
        {
            return "Sauvegarde des séries KO, cause : " + e.getMessage();
        }

        return "Sauvegarde des séries OK";
    }
}